<?php

namespace App\Http\Middleware;

use Illuminate\Http\Request;

final class AuthorizationMiddleware
{
    private const DELIMITER = '|';

    /**
     * @param string $roles
     * @param string $permissions
     * @return mixed
     */
    public function handle(Request $request, \Closure $next, $roles, $permissions)
    {
        if ( ! \is_array($roles)) {
            $roles = \explode(self::DELIMITER, $roles);
        }

        if ( ! \is_array($permissions)) {
            $permissions = \explode(self::DELIMITER, $permissions);
        }

        if (
            \Auth::guard()->guest()
            || ! \Auth::guard()
                ->user()
                ->hasAbility($roles, $permissions)
        ) {
            return $this->unauthorized();
        }

        return $next($request);
    }

    private function unauthorized()
    {
        return \abort(403, 'User does not have any of the necessary access rights.');
    }
}
